import ref from 'ref'
import {config} from '@/common/utils'
import FaceBase from '../../../sdk/arcface/FaceBase'
import FaceFR from '../../../sdk/arcface/FaceFR'
import FaceFD from '../../../sdk/arcface/FaceFD'
import FaceFT from '../../../sdk/arcface/FaceFT'

const aiconfig = config.get('aiconfig')

/**
 * 初始化人脸识别引擎
 */
export function FR_init() {
  // 分配给引擎使用的内存大小
  let FR_WORKBUF_SIZE = 400 * 1024 * 1024

  // 分配给引擎使用的内存地址
  let pFRWorkMem = FaceBase.malloc(FR_WORKBUF_SIZE)

  // 引擎handle
  let phFREngine = ref.ref(Buffer.alloc(FaceBase.MIntPtr_t.size))
  let ret = FaceFR.AFR_FSDK_InitialEngine(aiconfig.AppID, aiconfig.FR_key, pFRWorkMem, FR_WORKBUF_SIZE, phFREngine)
  if (ret === 0) {
    return ref.deref(phFREngine)
  } else {
    FaceBase.free(pFRWorkMem)
    throw new Error(`初始化人脸识别引擎失败:${ret}`)
  }
}

/**
 * 初始化人脸检测引擎
 */
export function FD_init() {
  // 分配给引擎使用的内存大小
  let FD_WORKBUF_SIZE = 20 * 1024 * 1024

  // 分配给引擎使用的内存地址
  let pFDWorkMem = FaceBase.malloc(FD_WORKBUF_SIZE)

  // 引擎handle
  let phFDEngine = ref.ref(Buffer.alloc(FaceBase.MIntPtr_t.size))
  let ret = FaceFD.AFD_FSDK_InitialFaceEngine(aiconfig.AppID, aiconfig.FD_key, pFDWorkMem, FD_WORKBUF_SIZE, phFDEngine, FaceFD.OrientPriority.AFD_FSDK_OPF_0_HIGHER_EXT, 16, 50)
  if (ret === 0) {
    return ref.deref(phFDEngine)
  } else {
    FaceBase.free(pFDWorkMem)
    throw new Error(`初始化人脸检测引擎失败:${ret}`)
  }
}

/**
 * 初始化人脸跟踪引擎
 */
export function FT_init() {
  // 分配给引擎使用的内存大小
  let FT_WORKBUF_SIZE = 30 * 1024 * 1024

  // 分配给引擎使用的内存地址
  let pFTWorkMem = FaceBase.malloc(FT_WORKBUF_SIZE)

  // 引擎handle
  let phFTEngine = ref.ref(Buffer.alloc(FaceBase.MIntPtr_t.size))
  let ret = FaceFT.AFT_FSDK_InitialFaceEngine(aiconfig.AppID, aiconfig.FT_key, pFTWorkMem, FT_WORKBUF_SIZE, phFTEngine, FaceFD.OrientPriority.AFD_FSDK_OPF_0_HIGHER_EXT, 16, 50)
  if (ret === 0) {
    return ref.deref(phFTEngine)
  } else {
    FaceBase.free(pFTWorkMem)
    throw new Error(`初始化人脸跟踪引擎失败:${ret}`)
  }
}
